package com.jkkc.lib.base.extend

import android.os.Handler
import android.view.MotionEvent
import android.view.View
import kotlin.math.abs

var lastTime = 0L
var clickCount = 0

fun View.continuousClick(count: Int, callback: () -> Unit) {
    this.setOnClickListener {
        if (lastTime == 0L) {
            lastTime = System.currentTimeMillis()
            clickCount++
        } else {
            if (System.currentTimeMillis() - lastTime > 1000L) {
                clickCount = 0
                lastTime = 0L
            } else {
                clickCount++
                lastTime = System.currentTimeMillis()
                if (clickCount >= count) {
                    callback()
                }
            }
        }
    }
}

//自定义长按事件
fun View.longClick(handler: Handler, delayMillis: Long, callback: () -> Unit) {
    this.setOnTouchListener(object : View.OnTouchListener {
        private val TOUCH_MAX = 50
        private var lastMotionX = 0
        private var lastMotionY = 0
        val r = Runnable { callback() }

        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            event?.let { event ->
                val x = event.x.toInt()
                val y = event.y.toInt()
                when (event.action) {
                    MotionEvent.ACTION_UP -> {
                        handler.removeCallbacks(r)
                    }
                    MotionEvent.ACTION_MOVE -> {
                        if (abs(lastMotionX - x) > TOUCH_MAX || abs(lastMotionY - y) > TOUCH_MAX) {
                            handler.removeCallbacks(r)
                        } else {

                        }
                    }
                    MotionEvent.ACTION_DOWN -> {
                        handler.removeCallbacks(r)
                        lastMotionX = x
                        lastMotionY = y
                        handler.postDelayed(r, delayMillis)
                    }
                    else -> handler.removeCallbacks(r)
                }
            }
            return true

        }

    })
}